<?php
header('Content-Type: application/json');

try {
    $messagesFile = '../admin/data/messages.json';  // 修改路径
    
    if (!file_exists($messagesFile)) {
        file_put_contents($messagesFile, json_encode(['messages' => [], 'next_id' => 1]));
    }
    
    $messages = json_decode(file_get_contents($messagesFile), true);
    
    // 只返回已审核通过的留言
    $approvedMessages = [
        'messages' => array_filter($messages['messages'], function($msg) {
            return isset($msg['status']) && $msg['status'] === 'approved';
        })
    ];
    
    // 重新索引数组
    $approvedMessages['messages'] = array_values($approvedMessages['messages']);
    
    // 按时间倒序排序
    usort($approvedMessages['messages'], function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    echo json_encode($approvedMessages);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?> 